package com.quasar.hpatient.module.home_inspection;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.ImageView;

import com.quasar.hpatient.R;
import com.quasar.hpatient.bean.comm_album.AlbumPhotoBean;
import com.quasar.hpatient.bean.home_inspection.InspectionBean;
import com.quasar.hpatient.dialog.AssayTitleDialog;
import com.quasar.hpatient.dialog.CalendarDialog;
import com.quasar.hpatient.dialog.CheckDialog;
import com.quasar.hpatient.dialog.EventDialog;
import com.quasar.hpatient.dialog.InputDoubleDialog;
import com.quasar.hpatient.dialog.ListDialog;
import com.quasar.hpatient.dialog.QualitativeDialog;
import com.quasar.hpatient.dialog.WarningDialog;
import com.quasar.hpatient.module.comm_album.AlbumActivity;
import com.quasar.hpatient.module.comm_camera.CameraActivity;
import com.quasar.hpatient.module.home_event.EventActivity;
import com.quasar.hpatient.module.home_health.HealthActivity;
import com.quasar.hpatient.module.home_inspection_chart.HomeInspectionChartActivity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import lib.quasar.base.frame.BaseActivity;
import lib.quasar.compress.CompressManager;
import lib.quasar.compress.OnCompressChangeListener;
import lib.quasar.context.BaseConstant;
import lib.quasar.util.CardUtil;
import lib.quasar.util.ImageUtil;
import lib.quasar.util.LogUtil;
import lib.quasar.widget.menu.NavigationView;
import lib.quasar.widget.photo.OnPhotoChangeListener;
import lib.quasar.widget.photo.PhotoLayout;
import lib.quasar.widget.photo.PhotoModel;

/**
 * description: 化验记录
 * created by kalu on 2018/4/10 10:26
 */
public class HomeInspectionActivity extends BaseActivity<HomeInspectionPresenter> implements HomeInspectionView {

    public final static int REQUEST_CODE = 1001;
    public final static int RESULT_CODE = 1002;

    @Override
    public int initView() {
        return R.layout.activity_home_inspection;
    }

    @Override
    public void initDataLocal() {

        final RecyclerView recycler = findViewById(R.id.home_inspection_list);
        getPresenter().initList(this, recycler);

        final NavigationView menu = findViewById(R.id.home_assay_menu);
        menu.setOnNavigation2ChangeListener((isBack, isMenu1, isMenu2) -> {
            if (isBack) onBackPressed();
            else if (isMenu1) {
                final Object tag = recycler.getTag();
                if (null == tag || HomeInspectionPresenter.INSPECTION_NULL.equals(tag)) {
                    toast("化验单未发生变化");
                } else if (HomeInspectionPresenter.INSPECTION_ONLY_PICTURE.equals(tag)) {
                    showSuggest();
                } else {
                    showWarning();
                }
            } else if (isMenu2) {
                String trim = getPresenter().getTime(HomeInspectionActivity.this, recycler);
                Intent intent = new Intent(HomeInspectionActivity.this, EventActivity.class);
                intent.putExtra(EventActivity.TIME, trim);
                startActivityForResult(intent, REQUEST_CODE);
            }
        });
    }


    @Override
    public void initDataNet() {

        final RecyclerView recycler = findViewById(R.id.home_inspection_list);
        final String datetime = getIntent().getStringExtra("time");
        getPresenter().setTime(HomeInspectionActivity.this, recycler, datetime);
        getPresenter().inspectionList(this, recycler, false, false);
    }

    @Override
    public void goSingle(CharSequence itemname, String unit) {

        Intent intent = new Intent(getApplicationContext(), HomeInspectionChartActivity.class);
        intent.putExtra(HomeInspectionChartActivity.NAME, itemname);
        intent.putExtra(HomeInspectionChartActivity.UNIT, unit);
        goNext(intent);
    }

    @Override
    public void showSuggest() {

        final WarningDialog dialog = new WarningDialog(this);
        dialog.show();
        dialog.setTitles("录入数据有利于医生对比病史\n\n确认只提交图片？");
        dialog.setButton("确定", "继续填写");
        dialog.setOnDialogChangeListener((left, right) -> {
            if (left) {
                showWarning();
            } else if (right) {
                toast("去完善");
            }
        });
    }

    @Override
    public void showWarning() {

        final WarningDialog dialog = new WarningDialog(this);
        dialog.show();
        dialog.setTitles("是否提交给医生诊断");
        dialog.setButton("否", "是");
        dialog.setOnDialogChangeListener((left, right) -> {
            ArrayList<InspectionBean.DoctorBean> mDoctor = new ArrayList<>();//空医生，取消和获取医生列表失败时容错使用
            if (left) {
                final RecyclerView recycler = findViewById(R.id.home_inspection_list);
                getPresenter().saveInspection(this, recycler, mDoctor);
            } else if (right) {
                final List<InspectionBean.DoctorBean> list = getPresenter().getDoctorList();
                if (list.size() > 0) {
                    showDoctor(list);
                } else {
                    final RecyclerView recycler = findViewById(R.id.home_inspection_list);
                    getPresenter().saveInspection(this, recycler, mDoctor);
                }
            }
        });
    }

    @Override
    public void showDoctor(List<InspectionBean.DoctorBean> list) {

        final CheckDialog dialog = new CheckDialog(this);
        //list为所有医生列表 datas为临时选中医生列表
        ArrayList<InspectionBean.DoctorBean> datas = new ArrayList();//选中医生
        dialog.setOnDialogChangeListener(list1 -> {
            for (int x = 0; x < list.size(); x++) {
                if (list.get(x).isCheck()) {
                    datas.add(list.get(x));
                }
            }
            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().saveInspection(this, recycler, datas);
        });
        dialog.show();
        dialog.setList(list);
        dialog.setTitle("选择医生");
        dialog.setButton("取消", "确定");
    }

    @Override
    public void showEvent(String time, List<InspectionBean.EventBean> list) {
        final EventDialog dialog = new EventDialog(this);
        dialog.show();
        dialog.setTitle(time);
        dialog.setList(list);
    }

    @Override
    public void showCalendar() {

        final CalendarDialog dialog = new CalendarDialog(this);
        final RecyclerView recycler = findViewById(R.id.home_inspection_list);
        dialog.setScroll(getPresenter().getTime(HomeInspectionActivity.this, recycler));
        dialog.show();
        dialog.setOnCalendarChangeListener((years, months, day, maxDay, isClick) -> {
            if (isClick) {
                getPresenter().setTime(HomeInspectionActivity.this, recycler, years + "-" + months + "-" + day);
                getPresenter().inspectionList(HomeInspectionActivity.this, recycler, false, false);
            } else {
                getPresenter().schemelList(dialog, years, months, day, maxDay);
            }
        });
    }

    @Override
    public void showAdd(int position, String inspectionname, String groupid) {

        AssayTitleDialog dialog = new AssayTitleDialog(this);
        dialog.setOnDialogChangeListener((menu, name, result, max, min, unit) -> {
            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().addInspection(HomeInspectionActivity.this, recycler, position, groupid, menu, name, result, min, max, unit);
        });
        dialog.show();
        dialog.setMenu(inspectionname);
        if (position != -1) {
            dialog.setMenuTitle("自定义检测项");
        } else {
            dialog.setMenuTitle("自定义化验单");
        }
        dialog.setName(position != -1);
    }

    @Override
    public void showPhoto(int defaultPosition, List<? extends PhotoModel> imageLittleUrlList, List<? extends PhotoModel> imageUrlList, List<ImageView> imageViews) {

        if (imageLittleUrlList.isEmpty() || imageUrlList.isEmpty() || imageViews.isEmpty())
            return;

        new PhotoLayout.Builder(this)
                .setPhotoLongPressSave(false)
                .setPhotoOpenTransAnim(false)
                .setPhotoDefaultPosition(defaultPosition)
                .setPhotoBackgroundColor(Color.BLACK)
                .setPhotoDefaultResource(R.mipmap.ic_launcher)
                .setPhotoViewList(imageViews)
                .setPhotoUrlList(imageUrlList)
                .setPhotoLittleUrlList(imageLittleUrlList)
                .setOnPhotoChangeListener(new OnPhotoChangeListener() {
                    @Override
                    protected void onDelete(int position) {
                        deleteImage(position);
                    }

                    @Override
                    protected void onSave(String imagePath, int imageWidth, int imageHeight, int position) {
                        AlbumPhotoBean model = new AlbumPhotoBean();
                        model.setPicture(imagePath);
                        model.setWidth(imageWidth);
                        model.setHeight(imageHeight);
                        final ArrayList<AlbumPhotoBean> list = new ArrayList();
                        list.add(model);
                        final RecyclerView recycler = findViewById(R.id.home_inspection_list);
                        getPresenter().uploadPhoto(HomeInspectionActivity.this, recycler, list, position);
                    }
                }).show();
    }

    @Override
    public void deleteImage(final int position) {

        WarningDialog dialog = new WarningDialog(this);
        dialog.setOnDialogChangeListener((left, right) -> {
            if (right) {
                final RecyclerView recycler = findViewById(R.id.home_inspection_list);
                getPresenter().deletePhoto(HomeInspectionActivity.this, recycler, position);
            }
        });
        dialog.show();
        dialog.setTitles("确定删除照片");
        dialog.setButton("否", "是");
    }

    @Override
    public void deleteModel(final int position) {

        WarningDialog dialog = new WarningDialog(this);
        dialog.setOnDialogChangeListener((left, right) -> {
            if (left) return;
            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().deleteInspection(HomeInspectionActivity.this, recycler, position);
        });
        dialog.show();
        dialog.setTitles(getResources().getString(R.string.dialog_delete_title));
        dialog.setButton("取消", "确定");
    }

    @Override
    public void showInput(int position, String mins, String maxs) {

        final InputDoubleDialog dialog = new InputDoubleDialog(this);
        dialog.show();
        dialog.setTitle("修改参考值");
        dialog.setMenu("最小参考值:", "最大参考值:");
        dialog.setInput(mins, maxs);
        dialog.setInputType(8194, 8194);
        dialog.setNumberFilter(3, 7);
        dialog.setOnDialogChangeListener((top, bottom) -> {
            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().editInspection(HomeInspectionActivity.this, recycler, position, top, bottom);
        });
    }

    @Override
    public void showQualitative(int position) {
        QualitativeDialog dialog = new QualitativeDialog(this);
        dialog.setOnDialogChangeListener(input -> {
            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().editInspection(HomeInspectionActivity.this, recycler, input, position);
        });
        dialog.show();
        dialog.setTitle(getResources().getString(R.string.dialog_qualitative_title));
    }

    @Override
    public void showList(List<? extends ListDialog.ListModel> list) {

        final ListDialog dialog = new ListDialog(this);
        dialog.show();
        dialog.setList(list);
        dialog.setOnDialogChangeListener(() -> {
            goNext(HealthActivity.class);
        });
    }

    @Override
    public void goAlbum(List<AlbumPhotoBean> mPhoto) {
        Intent intent = new Intent(getApplicationContext(), AlbumActivity.class);
        intent.putExtra(AlbumActivity.LIST, (Serializable) mPhoto);
        intent.putExtra(AlbumActivity.CAMERA, true);
        startActivityForResult(intent, REQUEST_CODE);
    }

    @SuppressLint("CheckResult")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == AlbumActivity.RESULT_CODE_OPEN_CAMERA) {
            Intent intent = new Intent(getApplicationContext(), CameraActivity.class);
            startActivityForResult(intent, REQUEST_CODE);
        } else if (resultCode == AlbumActivity.RESULT_CODE && null != data) {
            ArrayList<AlbumPhotoBean> list = data.getParcelableArrayListExtra(AlbumActivity.LIST);
            if (null == list || list.size() == 0) return;

            Observable.create((ObservableOnSubscribe<ArrayList<AlbumPhotoBean>>) e -> {
                final ArrayList<AlbumPhotoBean> temp = new ArrayList<>();
                // 压缩, 保存图片
                for (int i = 0; i < list.size(); i++) {
                    final AlbumPhotoBean image = list.get(i);
                    String path = image.getPicture();
                    String name = path.substring(path.lastIndexOf(File.separatorChar), path.length());
                    final int width = image.getWidth();
                    final int height = image.getHeight();
                    final long size = image.getSize();
                    // 获取bitmap
                    if (!image.needCompress()) {
                        final AlbumPhotoBean news = new AlbumPhotoBean();
                        news.setPicture(path);
                        news.setCheck(image.isCheck());
                        news.setWidth(width);
                        news.setHeight(height);
                        news.setSize(size);
                        temp.clear();
                        temp.add(news);
                        e.onNext(temp);

                    } else {

                        final Bitmap bitmap = ImageUtil.compressImageJava(path, image.calcuWidth(), image.calcuHeight());
                        final String floder = CardUtil.getSDCardPath() + BaseConstant.CACHE_COMPRESS;

                        // 压缩图片
                        CompressManager.syncCompress(true, image.getRatio(), floder, name, bitmap, new OnCompressChangeListener() {
                            @Override
                            public void onCompressStart() {
                            }

                            @Override
                            public void onCompressFinish(String filePath) {

                                if (null != bitmap) {
                                    bitmap.recycle();
                                }

                                final AlbumPhotoBean news = new AlbumPhotoBean();
                                news.setPicture(filePath);
                                news.setCheck(image.isCheck());
                                news.setWidth(width);
                                news.setHeight(height);
                                news.setSize(size);

                                temp.clear();
                                temp.add(news);
                                e.onNext(temp);
                            }

                            @Override
                            public void onCompressError(int errorNum, String description) {

                                if (null != bitmap) {
                                    bitmap.recycle();
                                }
                            }
                        });
                    }
                }
            }).subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(temp -> {
                                HomeInspectionPresenter presenter = getPresenter();
                                if (null == presenter) return;
                                final RecyclerView recycler = findViewById(R.id.home_inspection_list);
                                presenter.uploadPhoto(HomeInspectionActivity.this, recycler, temp, -1);
                                //  ToastUtil.showToast("分线程: 压缩图片结束");
                            }, throwable -> {
                                // ToastUtil.showToast("分线程: 压缩图片失败");
                                LogUtil.e("", throwable.getMessage(), throwable);
                            },
                            () -> {
                                // ToastUtil.showToast("分线程: 压缩图片结束");
                            },
                            disposable -> {
                                // ToastUtil.showToast("分线程: 开始压缩图片");
                            });
        } else if (resultCode == CameraActivity.RESULT_CODE && null != data) {
            final String path = data.getStringExtra(CameraActivity.PATH);
            final long size = data.getLongExtra(CameraActivity.SIZE, -1);
            final int width = data.getIntExtra(CameraActivity.WIDTH, -1);
            final int height = data.getIntExtra(CameraActivity.HEIGHT, -1);
            if (TextUtils.isEmpty(path)) {
                // ToastUtil.showToast("出现未知错误");
                return;
            }
            //  LogUtil.e("photo", "path = " + path + ", size = " + size + ", width = " + width + ", height = " + height);

            AlbumPhotoBean model = new AlbumPhotoBean();
            model.setPicture(path);
            model.setWidth(width);
            model.setHeight(height);
            model.setSize(size);

            final ArrayList<AlbumPhotoBean> list = new ArrayList();
            list.add(model);

            final RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().uploadPhoto(HomeInspectionActivity.this, recycler, list, -1);

        } else if (requestCode == requestCode && resultCode == EventActivity.RESULT_CODE) {
            final ArrayList<InspectionBean.EventBean> list = data.getParcelableArrayListExtra(EventActivity.LIST);
            RecyclerView recycler = findViewById(R.id.home_inspection_list);
            getPresenter().setEvent(this, recycler, list, true);
        }
    }
}